package com.image.util;

import com.sun.org.slf4j.internal.Logger;
import com.sun.org.slf4j.internal.LoggerFactory;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

public class HttpUtils {

    private final static Logger logger = LoggerFactory.getLogger(HttpUtils.class);
    private  static  String url = "";

    public static String doGet(String url) throws IOException {
        //创建HttpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url); //创建httpGet请求
        CloseableHttpResponse response = null;  //reponse对象

        try{
            response = httpClient.execute(httpGet); //执行httpGet请求
            if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){   //判断返回状态是否为200
                String content = EntityUtils.toString(response.getEntity(),"utf-8");
                return content;
            }
        }
        catch (IOException e){
            e.printStackTrace();
        } finally {
            if(response != null){   //关闭资源
                response.close();
            }
            httpClient.close();
        }
        return null;
    }

    public static void main(String[] args) throws IOException {
        String url = "https://club.jd.com/discussion/getProductPageImageCommentList.action?productId=100005920091&page=4";
        String content = HttpUtils.doGet(url);

        //JSONObject  {"a","1"}
        //JSONArray  ["a","1"]
        JSONObject result = JSONObject.fromObject(content);
        System.out.println("result:"+result);

        JSONObject imgComments = (JSONObject) result.get("imgComments");
        System.out.println("imgComments:"+imgComments);

        JSONArray imgList = (JSONArray) imgComments.get("imgList");
        System.out.println("imgList:"+imgList);

        JSONObject img = (JSONObject) imgList.get(0);
        System.out.println("img:"+img);

        String imageUrl = (String) img.get("imageUrl");
        System.out.println(imageUrl);
    }
}
